<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Opus } from '@/api/modules/opus'
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import apiOpus from '@/api/modules/opus'
import uploadApi from '@/api/modules/uploadImages.ts'
import ImagesUpload from '@/components/ImagesUpload/index.vue'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

// 百度翻译接口
const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}
const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}

// 特殊字符检验
const validateNoSpecialChars = (value: string) => {
  // 允许字母、数字、汉字、空格、基本标点和中英文逗号，以及 - _ .
  return /[#$%&?]/.test(value) // 移除了 - _ .
}

interface FileInfo {
  file: File
  previewUrl: string
  name: string
  size: number
  type: string
}

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  opusId: route.params.id as string | number ?? '',
  opusName: '',
  opusNameEn: '',
  opusUrls: [] as FileInfo[],
  opusDescription: '',
  opusDescriptionEn: '',
  status: 0,
  themeName: '',
  nickName: '',
  uid: '',
  userId: '',
})

const translateOpusNameToEnglish = async () => {
  if (form.value.opusName && form.value.opusName.trim() !== '') {
    form.value.opusNameEn = await translateToEnglish(form.value.opusName)
  }
}

const translateDescriptionToEnglish = async () => {
  if (form.value.opusDescription && form.value.opusDescription.trim() !== '') {
    form.value.opusDescriptionEn = await translateToEnglish(form.value.opusDescription)
  }
}

// 计算当前模式
const mode = computed(() => {
  if (route.name === 'opusReview') {
    return 'review'
  }
  if (route.name === 'opusCreate') {
    return 'create'
  }
  if (route.name === 'opusEdit') {
    return 'edit'
  }
  return 'view' // 默认查看模式
})

// 判断是否是编辑模式且当前用户是数据所有者
const isEdit = computed(() => {
  const isEditMode = mode.value === 'edit'
  const isOwner = form.value.userId && form.value.uid && form.value.userId === form.value.uid
  return isEditMode ? !isOwner : false
})
const isReviewMode = computed(() => {
  return mode.value === 'review' && form.value.status === 0
})

const isViewMode = computed(() => {
  return mode.value === 'review' && form.value.status !== 0
})

const isOwner = computed(() => {
  return form.value.userId && form.value.uid && form.value.userId === form.value.uid
})
const showEditActions = computed(() => {
  return mode.value === 'edit' && isOwner.value
})
// 接收大赛id
const themeId = ref<number>(route.query.themeId ? Number(route.query.themeId) : 0)
const formRules = ref<FormRules>({
  opusName: [
    { required: true, message: '请输入作品名称', trigger: 'blur' },
    { max: 50, message: '作品名称长度不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  opusNameEn: [
    { required: true, message: '请输入作品英文名称', trigger: 'blur' },
    { max: 250, message: '作品英文名称长度不能超过500个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 检查是否包含中文
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('不能包含中文字符'))
          return
        }

        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  opusDescription: [
    { required: true, message: '请输入作品简介', trigger: 'blur' },
    { max: 200, message: '简介长度不能超过200个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  opusDescriptionEn: [
    { required: true, message: '请输入作品英文简介', trigger: 'blur' },
    { max: 1000, message: '英文简介长度不能超过200个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 检查是否包含中文
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('不能包含中文字符'))
          return
        }

        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  opusUrls: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少上传一张作品照片'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

onMounted(() => {
  if (form.value.opusId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  apiOpus.detail(form.value.opusId).then((res: any) => {
    loading.value = false
    const data = res.data

    // 将后端返回的字符串URL转换为数组
    const urlArray = data.opusUrl ? data.opusUrl.split(',') : []

    form.value.opusId = data.opusId
    form.value.opusName = data.opusName
    form.value.opusNameEn = data.opusNameEn
    form.value.opusDescription = data.opusDescription
    form.value.opusDescriptionEn = data.opusDescriptionEn
    form.value.status = data.status
    form.value.themeName = data.themeName
    form.value.nickName = data.nickName
    form.value.userId = data.userId
    form.value.uid = data.uid
    // 将URL字符串转换为数组
    form.value.opusUrls = urlArray.map((url: string) => ({
      previewUrl: url,
      name: url.split('/').pop() || '',
      size: 0,
      type: 'image/jpeg',
      file: new File([], ''), // 编辑模式下不需要实际的文件对象
    }))
  })
}

async function onSubmit() {
  try {
    loading.value = true
    await formRef.value?.validate()

    // 处理文件上传 (如果有新上传的文件)
    const newFiles = form.value.opusUrls.filter(item => item.file.size > 0)
    let uploadedUrls: string[] = []

    if (newFiles.length > 0) {
      const formData = new FormData()
      newFiles.forEach((fileInfo) => {
        formData.append('files', fileInfo.file)
      })
      const uploadRes = await uploadApi.uploadImages(formData)
      uploadedUrls = uploadRes.data
    }
    //  合并已有的URL和新上传的URL
    const existingUrls = form.value.opusUrls
      .filter(item => !item.file.size && item.previewUrl)
      .map(item => item.previewUrl)
    const allUrls = [...existingUrls, ...uploadedUrls].join(',')

    //  构建提交数据
    const opusData: Opus = {
      opusId: Number(form.value.opusId),
      opusName: form.value.opusName,
      opusNameEn: form.value.opusNameEn,
      opusDescription: form.value.opusDescription,
      opusDescriptionEn: form.value.opusDescriptionEn,
      status: form.value.status,
      themeId: themeId.value,
      opusUrl: allUrls, // 包含所有图片URL
    }
    if (mode.value === 'create') {
      await apiOpus.create(opusData)
      ElMessage.success('新增成功')
    }
    else if (mode.value === 'edit' || mode.value === 'review') {
      await apiOpus.edit(opusData)
      ElMessage.success('编辑成功')
    }

    goBack()
  }
  catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请稍后再试')
  }
  finally {
    loading.value = false
  }
}

function onCancel() {
  goBack()
}

function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'opus' })
  }
  else {
    router.push({ name: 'opus' })
  }
}

async function handlePhotoSuccess(options: { file: File }) {
  updateImg.value = true
  try {
    const previewUrl = URL.createObjectURL(options.file)
    form.value.opusUrls = [...form.value.opusUrls, {
      file: options.file,
      previewUrl,
      name: options.file.name,
      size: options.file.size,
      type: options.file.type,
    }]
    ElMessage.success('添加成功')
  }
  catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败')
  }
  finally {
    updateImg.value = false
  }
}

// // 通过作品
// function onApprove() {
//   form.value.status = 1
//   onSubmit()
// }
//
// // 驳回作品
// function onReject() {
//   form.value.status = 2
//   onSubmit()
// }

// 在组件卸载时清理预览URL
onBeforeUnmount(() => {
  form.value.opusUrls.forEach((item) => {
    if (item.previewUrl && item.previewUrl.startsWith('blob:')) {
      URL.revokeObjectURL(item.previewUrl)
    }
  })
})
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="mode === 'create' ? '新增作品' : '编辑作品'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <!-- 作者和大赛名称（只读） -->
        <template v-if="form.opusId !== ''">
          <ElFormItem label="作者" prop="userName">
            <ElInput v-model="form.nickName" disabled />
          </ElFormItem>
          <ElFormItem label="大赛名称" prop="userName">
            <ElInput v-model="form.themeName" disabled />
          </ElFormItem>
        </template>

        <!-- 作品信息（根据模式显示不同状态） -->
        <ElFormItem label="作品名称" prop="opusName">
          <ElInput
            v-model="form.opusName"
            placeholder="请输入作品名称"
            maxlength="50"
            show-word-limit
            :disabled="mode === 'review' || mode === 'view' || isEdit"
          >
            <template #append>
              <ElButton @click="translateOpusNameToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>
        <ElFormItem label="作品英文名称" prop="opusNameEn">
          <ElInput
            v-model="form.opusNameEn"
            placeholder="请输入作品英文名称"
            maxlength="250"
            show-word-limit
            :disabled="mode === 'review' || mode === 'view' || isEdit"
          />
        </ElFormItem>
        <ElFormItem label="作品简介" prop="opusDescription">
          <ElInput
            v-model="form.opusDescription"
            placeholder="请输入作品简介"
            maxlength="200"
            show-word-limit
            :disabled="mode === 'review' || mode === 'view' || isEdit"
          >
            <template #append>
              <ElButton @click="translateDescriptionToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>
        <ElFormItem label="作品英文简介" prop="opusDescriptionEn">
          <ElInput
            v-model="form.opusDescriptionEn"
            placeholder="请输入作品英文简介"
            maxlength="1000"
            show-word-limit
            :disabled="mode === 'review' || mode === 'view' || isEdit"
          />
        </ElFormItem>
        <ElFormItem label="上传作品图片" prop="opusUrls">
          <!-- 新增模式使用上传组件 -->
          <ImagesUpload
            v-if="mode === 'create'"
            v-model="form.opusUrls"
            :limit="9"
            :size="10"
            multiple
            action=""
            :loading="updateImg"
            name="opusUrls"
            :width="150"
            :height="150"
            :http-request="handlePhotoSuccess"
          />

          <!-- 编辑模式使用预览组件 -->
          <div v-else class="image-preview-container">
            <ImagePreview
              v-for="(opus, index) in form.opusUrls"
              :key="index"
              :src="opus.previewUrl"
              :width="150"
              :height="150"
              class="preview-item"
            />
          </div>
        </ElFormItem>

        <FaFixedActionBar>
          <!-- 批阅模式 -->
          <template v-if="isReviewMode">
            <!--            <ElButton size="large" type="success" @click="onApprove"> -->
            <!--              通过 -->
            <!--            </ElButton> -->
            <!--            <ElButton size="large" type="danger" @click="onReject"> -->
            <!--              驳回 -->
            <!--            </ElButton> -->
            <ElButton size="large" @click="onCancel">
              取消
            </ElButton>
          </template>

          <!-- 查看模式下的按钮 -->
          <template v-else-if="isViewMode">
            <ElButton size="large" @click="onCancel">
              返回
            </ElButton>
          </template>

          <!-- 创建模式 -->
          <template v-else-if="mode === 'create'">
            <ElButton size="large" @click="onSubmit">
              提交
            </ElButton>
            <ElButton size="large" @click="onCancel">
              取消
            </ElButton>
          </template>

          <!-- 编辑模式 - 自己的作品 -->
          <template v-else-if="showEditActions">
            <ElButton size="large" @click="onSubmit">
              提交
            </ElButton>
            <ElButton size="large" @click="onCancel">
              取消
            </ElButton>
          </template>

          <!-- 编辑模式 - 别人的作品或其他情况 -->
          <template v-else>
            <ElButton size="large" @click="onCancel">
              返回
            </ElButton>
          </template>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
